package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/spit")
public class SpitController {

    @Autowired
    private SpitService spitService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(method = RequestMethod.GET)
    public Result findAll(){
        return new Result(true, StatusCode.OK,"查询成功", spitService.findAll());
    }

    @RequestMapping(method = RequestMethod.GET,value = "/{spitid}")
    public Result findById(@PathVariable String spitid){
        return new Result(true, StatusCode.OK,"查询成功", spitService.findById(spitid));
    }


    @RequestMapping(method = RequestMethod.POST)
    public Result save(@RequestBody Spit spit){
        spitService.add(spit);
        return new Result(true, StatusCode.OK,"保存成功");
    }

    @RequestMapping(method = RequestMethod.PUT,value = "/{spitid}")
    public Result update(@PathVariable String spitid,@RequestBody Spit spit){
        spit.set_id(spitid);
        spitService.update(spit);
        return new Result(true, StatusCode.OK,"更新成功");
    }

    @RequestMapping(method = RequestMethod.DELETE,value = "/{spitid}")
    public Result deleteById(@PathVariable String spitid){
        spitService.deleteById(spitid);
        return new Result(true, StatusCode.OK,"删除成功");
    }
    @RequestMapping(method = RequestMethod.GET,value = "/comment/{parentid}/{page}/{size}")
    public Result findByParentid(@PathVariable("parentid") String parentid,@PathVariable("page") int page,@PathVariable("size") int size){
        Page<Spit> pageable = spitService.findByParentid(parentid, page, size);
        return new Result(true, StatusCode.OK,"查询成功",new PageResult<Spit>(pageable.getTotalElements(),pageable.getContent() ));
    }

    @RequestMapping(method = RequestMethod.PUT,value = "/thumbup/{spitid}")
    public Result thumbup(@PathVariable("spitid") String spitid){
        //判断当前用户是否已点赞，目前没有做认证，先把userid写死
        String userid = "111";
        //redis判断用户是否点赞
        if (redisTemplate.opsForValue().get("thumbup_"+ userid) != null) {
            return new Result(false, StatusCode.REPERROR,"不能重复点赞");
        };
        spitService.thumbup(spitid);
        //1 为标识
        redisTemplate.opsForValue().set("thumbup_"+ userid,1);
        return new Result(true, StatusCode.OK,"点赞成功");
    }
}
